const fs = require('fs');
const path = require('path');

/**
 * 超深度上下文学习系统
 * 
 * 学习目标：
 * 1. 源码维度：cpp源码 + 同目录GN + 父目录GN + 兄弟文件 + 兄弟目录的cpp和GN
 * 2. 测试维度：对应test文件 + test目录GN + test父目录GN + test兄弟目录关系
 * 3. Fuzz维度：对应fuzz文件 + fuzz目录GN + fuzz父目录GN + fuzz兄弟目录关系
 * 4. Mock维度：mock目录 + mock文件 + mock GN关系
 * 
 * 构建完整的文件关系图谱
 */
class UltraDeepContextLearner {
    constructor(ohcodeDir) {
        this.ohcodeDir = ohcodeDir;
        this.contextGraph = {
            // 源文件上下文（以源文件为key）
            sourceContexts: [],
            
            // 测试文件上下文
            testContexts: [],
            
            // Fuzz文件上下文
            fuzzContexts: [],
            
            // Mock文件上下文
            mockContexts: [],
            
            // 源文件 → 测试文件 映射
            sourceToTestMapping: {},
            
            // 源文件 → Fuzz文件 映射
            sourceToFuzzMapping: {},
            
            // 测试文件 → Mock文件 映射（新增）
            testToMockMapping: {},
            
            // Mock使用模式（新增）
            mockUsagePatterns: [],
            
            // GN文件关系图谱
            gnRelationships: [],
            
            // 统计
            stats: {
                totalSourceFiles: 0,
                totalTestFiles: 0,
                totalFuzzFiles: 0,
                totalMockFiles: 0,
                totalGNFiles: 0,
                sourceWithTest: 0,
                sourceWithFuzz: 0,
                testWithMock: 0  // 新增
            }
        };
    }

    /**
     * 主学习流程
     */
    async run() {
        console.log('🚀 Foundation增强学习（追加模式）...\n');
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('📌 学习范围: OHCode/foundation (110个核心项目)');
        console.log('📌 模式: 追加到现有知识库，不丢失原有数据');
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
        
        const startTime = Date.now();
        
        // 步骤1：扫描所有项目
        console.log('📦 步骤1: 扫描所有项目...\n');
        this.allProjects = await this.scanAllProjects();
        console.log(`   ✅ 发现 ${this.allProjects.length} 个项目\n`);
        
        // 步骤2：构建源文件上下文
        console.log('📂 步骤2: 构建源文件上下文...\n');
        await this.buildSourceContexts();
        console.log(`   ✅ 构建了 ${this.contextGraph.sourceContexts.length} 个源文件上下文\n`);
        
        // 步骤3：构建测试文件上下文
        console.log('🧪 步骤3: 构建测试文件上下文...\n');
        await this.buildTestContexts();
        console.log(`   ✅ 构建了 ${this.contextGraph.testContexts.length} 个测试文件上下文\n`);
        
        // 步骤4：构建Fuzz文件上下文
        console.log('🎯 步骤4: 构建Fuzz文件上下文...\n');
        await this.buildFuzzContexts();
        console.log(`   ✅ 构建了 ${this.contextGraph.fuzzContexts.length} 个Fuzz文件上下文\n`);
        
        // 步骤5：构建Mock文件上下文
        console.log('🎭 步骤5: 构建Mock文件上下文...\n');
        await this.buildMockContexts();
        console.log(`   ✅ 构建了 ${this.contextGraph.mockContexts.length} 个Mock文件上下文\n`);
        
        // 步骤6：建立文件映射关系
        console.log('🔗 步骤6: 建立文件映射关系...\n');
        await this.buildFileMappings();
        console.log(`   ✅ 建立了 ${Object.keys(this.contextGraph.sourceToTestMapping).length} 个源→测试映射\n`);
        console.log(`   ✅ 建立了 ${Object.keys(this.contextGraph.sourceToFuzzMapping).length} 个源→Fuzz映射\n`);
        
        // 步骤7：分析GN关系
        console.log('📐 步骤7: 分析GN关系图谱...\n');
        await this.analyzeGNRelationships();
        console.log(`   ✅ 分析了 ${this.contextGraph.gnRelationships.length} 个GN关系\n`);
        
        // 步骤8：保存结果
        await this.saveResults();
        
        const duration = ((Date.now() - startTime) / 1000).toFixed(2);
        
        console.log(`\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
        console.log(`✅ 学习完成！耗时: ${duration} 秒`);
        
        this.printSummary();
    }

    /**
     * 扫描所有项目
     */
    async scanAllProjects() {
        const projects = [];
        
        const scanDir = (dir, depth = 0) => {
            if (depth > 5) return;
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                const hasBundleJson = entries.some(e => e.name === 'bundle.json');
                
                if (hasBundleJson) {
                    projects.push(dir);
                    return;
                }
                
                for (const entry of entries) {
                    if (entry.isDirectory() && !entry.name.startsWith('.') && 
                        entry.name !== 'node_modules' && entry.name !== 'out') {
                        scanDir(path.join(dir, entry.name), depth + 1);
                    }
                }
            } catch (e) {}
        };
        
        // 🎯 Foundation专项学习：只扫描foundation目录
        const topDirs = ['foundation'];
        for (const dir of topDirs) {
            const fullPath = path.join(this.ohcodeDir, dir);
            if (fs.existsSync(fullPath)) {
                console.log(`   🔍 扫描 ${dir} 目录...`);
                scanDir(fullPath);
            }
        }
        
        return projects;
    }

    /**
     * 步骤2：构建源文件上下文（全面学习，不设限制）
     */
    async buildSourceContexts() {
        let processedCount = 0;
        const sampleLimit = 20000; // Foundation专项：大幅提高限制
        
        for (const project of this.allProjects) {
            if (processedCount >= sampleLimit) break;
            
            // 查找所有源文件（排除test目录）
            const sourceFiles = this.findSourceFiles(project, ['test', 'tests', 'mock']);
            
            for (const sourceFile of sourceFiles) {
                if (processedCount >= sampleLimit) break;
                
                const context = await this.buildFileContext(sourceFile, 'source', project);
                if (context) {
                    this.contextGraph.sourceContexts.push(context);
                    this.contextGraph.stats.totalSourceFiles++;
                    processedCount++;
                    
                    if (processedCount % 100 === 0) {
                        console.log(`      已处理 ${processedCount} 个源文件...`);
                    }
                }
            }
        }
    }

    /**
     * 步骤3：构建测试文件上下文（增强版：递归扫描所有子模块的test目录）
     */
    async buildTestContexts() {
        let processedCount = 0;
        const sampleLimit = 10000; // 大幅提高限制，充分学习所有UT
        
        console.log('   🔍 递归扫描所有子模块的 test 目录...\n');
        
        for (const project of this.allProjects) {
            if (processedCount >= sampleLimit) break;
            
            // 🔥 关键改进：递归查找项目下所有的 test/unittest 目录
            const allTestDirs = this.findAllTestDirectories(project);
            console.log(`      [${path.basename(project)}] 发现 ${allTestDirs.length} 个测试目录`);
            
            for (const testDir of allTestDirs) {
                if (processedCount >= sampleLimit) break;
                
                const testFiles = this.findTestFiles(testDir);
                
                for (const testFile of testFiles) {
                    if (processedCount >= sampleLimit) break;
                    
                    const context = await this.buildFileContext(testFile, 'test', project);
                    if (context) {
                        // 🔥 重点：深入分析测试函数内容
                        await this.deepAnalyzeTestFunctions(testFile, context);
                        
                        this.contextGraph.testContexts.push(context);
                        this.contextGraph.stats.totalTestFiles++;
                        processedCount++;
                        
                        if (processedCount % 100 === 0) {
                            console.log(`      已处理 ${processedCount} 个测试文件...`);
                        }
                    }
                }
            }
        }
    }

    /**
     * 🔥 递归查找项目下所有的 test/unittest 目录
     */
    findAllTestDirectories(projectRoot) {
        const testDirs = [];
        
        const scanForTestDirs = (dir, depth = 0) => {
            if (depth > 10) return; // 最多10层深度
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    if (!entry.isDirectory()) continue;
                    if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'out') continue;
                    
                    const fullPath = path.join(dir, entry.name);
                    
                    // 检查是否是 test 目录
                    if (entry.name === 'test' || entry.name === 'tests') {
                        // 查找其下的 unittest/unittests 子目录
                        const unittestPath = path.join(fullPath, 'unittest');
                        const unittestsPath = path.join(fullPath, 'unittests');
                        
                        if (fs.existsSync(unittestPath)) {
                            testDirs.push(unittestPath);
                        } else if (fs.existsSync(unittestsPath)) {
                            testDirs.push(unittestsPath);
                        } else {
                            // test 目录本身
                            testDirs.push(fullPath);
                        }
                    }
                    
                    // 继续向下递归（除非已经在test目录下）
                    if (entry.name !== 'test' && entry.name !== 'tests') {
                        scanForTestDirs(fullPath, depth + 1);
                    }
                }
            } catch (e) {}
        };
        
        scanForTestDirs(projectRoot);
        return testDirs;
    }

    /**
     * 步骤4：构建Fuzz文件上下文（增强版：递归扫描所有子模块的fuzz目录）
     */
    async buildFuzzContexts() {
        let processedCount = 0;
        const sampleLimit = 5000; // 大幅提高限制，充分学习所有Fuzz
        
        console.log('   🔍 递归扫描所有子模块的 fuzz 目录...\n');
        
        for (const project of this.allProjects) {
            if (processedCount >= sampleLimit) break;
            
            // 🔥 关键改进：递归查找项目下所有的 test/fuzztest 目录
            const allFuzzDirs = this.findAllFuzzDirectories(project);
            if (allFuzzDirs.length > 0) {
                console.log(`      [${path.basename(project)}] 发现 ${allFuzzDirs.length} 个Fuzz目录`);
            }
            
            for (const fuzzDir of allFuzzDirs) {
                if (processedCount >= sampleLimit) break;
                
                const fuzzFiles = this.findFuzzFiles(fuzzDir);
                
                for (const fuzzFile of fuzzFiles) {
                    if (processedCount >= sampleLimit) break;
                    
                    const context = await this.buildFileContext(fuzzFile, 'fuzz', project);
                    if (context) {
                        // 🔥 重点：深入分析Fuzzer函数内容
                        await this.deepAnalyzeFuzzerFunctions(fuzzFile, context);
                        
                        this.contextGraph.fuzzContexts.push(context);
                        this.contextGraph.stats.totalFuzzFiles++;
                        processedCount++;
                        
                        if (processedCount % 50 === 0) {
                            console.log(`      已处理 ${processedCount} 个Fuzz文件...`);
                        }
                    }
                }
            }
        }
    }

    /**
     * 🔥 递归查找项目下所有的 test/fuzztest 目录
     */
    findAllFuzzDirectories(projectRoot) {
        const fuzzDirs = [];
        
        const scanForFuzzDirs = (dir, depth = 0) => {
            if (depth > 10) return;
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    if (!entry.isDirectory()) continue;
                    if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'out') continue;
                    
                    const fullPath = path.join(dir, entry.name);
                    
                    // 检查是否是 fuzztest/fuzz 目录
                    if (entry.name === 'fuzztest' || entry.name === 'fuzz') {
                        fuzzDirs.push(fullPath);
                    }
                    // 检查是否是 test/tests 目录，查找其下的 fuzztest/fuzz
                    else if (entry.name === 'test' || entry.name === 'tests') {
                        const fuzztest = path.join(fullPath, 'fuzztest');
                        const fuzz = path.join(fullPath, 'fuzz');
                        
                        if (fs.existsSync(fuzztest)) {
                            fuzzDirs.push(fuzztest);
                        }
                        if (fs.existsSync(fuzz)) {
                            fuzzDirs.push(fuzz);
                        }
                    }
                    // 继续向下递归
                    else {
                        scanForFuzzDirs(fullPath, depth + 1);
                    }
                }
            } catch (e) {}
        };
        
        scanForFuzzDirs(projectRoot);
        return fuzzDirs;
    }

    /**
     * 步骤5：构建Mock文件上下文（增强版：递归扫描所有子模块的mock目录）
     */
    async buildMockContexts() {
        let processedCount = 0;
        const sampleLimit = 5000; // 大幅提高限制，充分学习所有Mock
        
        console.log('   🔍 递归扫描所有子模块的 mock 目录...\n');
        
        for (const project of this.allProjects) {
            if (processedCount >= sampleLimit) break;
            
            // 🔥 关键改进：递归查找项目下所有的 mock 文件
            const mockFiles = this.findAllMockFiles(project);
            if (mockFiles.length > 0) {
                console.log(`      [${path.basename(project)}] 发现 ${mockFiles.length} 个Mock文件`);
            }
            
            for (const mockFile of mockFiles) {
                if (processedCount >= sampleLimit) break;
                
                const context = await this.buildFileContext(mockFile, 'mock', project);
                if (context) {
                    // 🔥 重点：深入分析Mock类实现
                    await this.deepAnalyzeMockImplementation(mockFile, context);
                    
                    this.contextGraph.mockContexts.push(context);
                    this.contextGraph.stats.totalMockFiles++;
                    processedCount++;
                    
                    if (processedCount % 50 === 0) {
                        console.log(`      已处理 ${processedCount} 个Mock文件...`);
                    }
                }
            }
        }
    }

    /**
     * 🔥 递归查找项目下所有的 Mock 文件
     */
    findAllMockFiles(projectRoot) {
        const mockFiles = [];
        
        const scanForMockFiles = (dir, depth = 0) => {
            if (depth > 10 || mockFiles.length >= 1000) return;
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    const fullPath = path.join(dir, entry.name);
                    
                    if (entry.isDirectory()) {
                        if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'out') continue;
                        
                        // 继续递归
                        scanForMockFiles(fullPath, depth + 1);
                    } else if (entry.isFile()) {
                        // 查找Mock文件
                        if ((entry.name.toLowerCase().includes('mock') || 
                             fullPath.includes('/mock/') || fullPath.includes('\\mock\\')) &&
                            (entry.name.endsWith('.cpp') || entry.name.endsWith('.h'))) {
                            mockFiles.push(fullPath);
                        }
                    }
                }
            } catch (e) {}
        };
        
        scanForMockFiles(projectRoot);
        return mockFiles;
    }

    /**
     * 构建单个文件的完整上下文
     */
    async buildFileContext(filePath, fileType, projectRoot) {
        try {
            const fileDir = path.dirname(filePath);
            const fileName = path.basename(filePath);
            const parentDir = path.dirname(fileDir);
            
            // 1. 当前文件信息
            const fileContent = this.safeReadFile(filePath);
            if (!fileContent) return null;
            
            const context = {
                // === 基础信息 ===
                filePath: path.relative(projectRoot, filePath),
                fileName: fileName,
                fileType: fileType,
                fileSize: fileContent.length,
                
                // === 文件内容特征 ===
                includes: this.extractIncludes(fileContent),
                functions: this.extractFunctionSignatures(fileContent),
                classes: this.extractClasses(fileContent),
                namespaces: this.extractNamespaces(fileContent),
                hwtest_cases: fileType === 'test' ? this.extractHWTestCases(fileContent) : [],
                
                // === 同目录上下文 ===
                sameDirGN: null,
                sameDirCppFiles: [],
                sameDirHeaderFiles: [],
                
                // === 父目录上下文 ===
                parentDirGN: null,
                parentDirStructure: null,
                
                // === 兄弟目录上下文 ===
                siblingDirs: [],
                siblingDirFiles: []
            };
            
            // 2. 同目录的GN文件
            const sameDirGNPath = path.join(fileDir, 'BUILD.gn');
            if (fs.existsSync(sameDirGNPath)) {
                context.sameDirGN = {
                    path: path.relative(projectRoot, sameDirGNPath),
                    content: this.parseGNFile(sameDirGNPath)
                };
            }
            
            // 3. 同目录的cpp和h文件
            try {
                const sameDirEntries = fs.readdirSync(fileDir, { withFileTypes: true });
                for (const entry of sameDirEntries) {
                    if (entry.isFile()) {
                        if (entry.name.endsWith('.cpp') || entry.name.endsWith('.cc')) {
                            context.sameDirCppFiles.push(entry.name);
                        } else if (entry.name.endsWith('.h') || entry.name.endsWith('.hpp')) {
                            context.sameDirHeaderFiles.push(entry.name);
                        }
                    }
                }
            } catch (e) {}
            
            // 4. 父目录的GN文件
            const parentDirGNPath = path.join(parentDir, 'BUILD.gn');
            if (fs.existsSync(parentDirGNPath)) {
                context.parentDirGN = {
                    path: path.relative(projectRoot, parentDirGNPath),
                    content: this.parseGNFile(parentDirGNPath)
                };
            }
            
            // 5. 父目录结构
            try {
                const parentDirEntries = fs.readdirSync(parentDir, { withFileTypes: true });
                context.parentDirStructure = {
                    subdirs: parentDirEntries.filter(e => e.isDirectory()).map(e => e.name),
                    hasTest: parentDirEntries.some(e => e.isDirectory() && (e.name === 'test' || e.name === 'tests')),
                    hasMock: parentDirEntries.some(e => e.isDirectory() && e.name === 'mock')
                };
            } catch (e) {}
            
            // 6. 兄弟目录信息
            if (context.parentDirStructure) {
                for (const siblingDirName of context.parentDirStructure.subdirs.slice(0, 10)) {
                    const siblingDirPath = path.join(parentDir, siblingDirName);
                    const siblingGNPath = path.join(siblingDirPath, 'BUILD.gn');
                    
                    const siblingInfo = {
                        dirName: siblingDirName,
                        hasGN: fs.existsSync(siblingGNPath),
                        gnContent: null,
                        cppCount: 0,
                        headerCount: 0
                    };
                    
                    if (siblingInfo.hasGN) {
                        siblingInfo.gnContent = this.parseGNFile(siblingGNPath);
                    }
                    
                    // 统计兄弟目录的文件
                    try {
                        const siblingEntries = fs.readdirSync(siblingDirPath, { withFileTypes: true });
                        siblingInfo.cppCount = siblingEntries.filter(e => 
                            e.isFile() && (e.name.endsWith('.cpp') || e.name.endsWith('.cc'))
                        ).length;
                        siblingInfo.headerCount = siblingEntries.filter(e => 
                            e.isFile() && (e.name.endsWith('.h') || e.name.endsWith('.hpp'))
                        ).length;
                    } catch (e) {}
                    
                    context.siblingDirs.push(siblingInfo);
                }
            }
            
            return context;
            
        } catch (e) {
            return null;
        }
    }

    /**
     * 步骤6：建立文件映射关系（智能匹配）
     */
    async buildFileMappings() {
        console.log('   🔍 使用智能匹配算法...\n');
        
        // === 策略1: 测试文件 → 源文件（精确匹配）===
        let unmappedTests = [];
        for (const testContext of this.contextGraph.testContexts) {
            const testBaseName = testContext.fileName
                .replace(/_test\.cpp$|_unittest\.cpp$/i, '')
                .replace(/^test_/i, '');
            
            let matched = false;
            
            // 1.1 精确文件名匹配
            for (const sourceContext of this.contextGraph.sourceContexts) {
                const sourceBaseName = path.basename(sourceContext.fileName, path.extname(sourceContext.fileName));
                
                if (testBaseName === sourceBaseName) {
                    if (!this.contextGraph.sourceToTestMapping[sourceContext.filePath]) {
                        this.contextGraph.sourceToTestMapping[sourceContext.filePath] = [];
                    }
                    this.contextGraph.sourceToTestMapping[sourceContext.filePath].push(testContext.filePath);
                    matched = true;
                    break;
                }
            }
            
            if (!matched) unmappedTests.push(testContext);
        }
        
        // === 策略2: 模糊匹配（目录相似度）===
        for (const testContext of unmappedTests) {
            const testBaseName = testContext.fileName
                .replace(/_test\.cpp$|_unittest\.cpp$/i, '')
                .replace(/^test_/i, '');
            
            let bestMatch = null;
            let bestScore = 0;
            
            for (const sourceContext of this.contextGraph.sourceContexts) {
                const sourceBaseName = path.basename(sourceContext.fileName, path.extname(sourceContext.fileName));
                
                // 2.1 部分匹配
                if (testBaseName.includes(sourceBaseName) || sourceBaseName.includes(testBaseName)) {
                    // 计算目录相似度
                    const testDirParts = path.dirname(testContext.filePath).split(path.sep);
                    const sourceDirParts = path.dirname(sourceContext.filePath).split(path.sep);
                    
                    let commonParts = 0;
                    for (let i = 0; i < Math.min(testDirParts.length, sourceDirParts.length); i++) {
                        if (testDirParts[i] === sourceDirParts[i]) {
                            commonParts++;
                        }
                    }
                    
                    const score = commonParts / Math.max(testDirParts.length, sourceDirParts.length);
                    if (score > bestScore) {
                        bestScore = score;
                        bestMatch = sourceContext;
                    }
                }
            }
            
            if (bestMatch && bestScore > 0.3) {
                if (!this.contextGraph.sourceToTestMapping[bestMatch.filePath]) {
                    this.contextGraph.sourceToTestMapping[bestMatch.filePath] = [];
                }
                this.contextGraph.sourceToTestMapping[bestMatch.filePath].push(testContext.filePath);
            }
        }
        
        // === 策略3: Fuzz文件 → 源文件 ===
        for (const fuzzContext of this.contextGraph.fuzzContexts) {
            const fuzzBaseName = fuzzContext.fileName.replace(/_fuzzer\.cpp$/i, '');
            
            let matched = false;
            
            // 3.1 精确匹配
            for (const sourceContext of this.contextGraph.sourceContexts) {
                const sourceBaseName = path.basename(sourceContext.fileName, path.extname(sourceContext.fileName));
                
                if (fuzzBaseName === sourceBaseName || fuzzBaseName.includes(sourceBaseName)) {
                    if (!this.contextGraph.sourceToFuzzMapping[sourceContext.filePath]) {
                        this.contextGraph.sourceToFuzzMapping[sourceContext.filePath] = [];
                    }
                    this.contextGraph.sourceToFuzzMapping[sourceContext.filePath].push(fuzzContext.filePath);
                    matched = true;
                    break;
                }
            }
            
            // 3.2 如果未匹配，尝试NDK接口匹配（OH_开头的函数）
            if (!matched && fuzzContext.functions && fuzzContext.functions.length > 0) {
                const ndkFunctions = fuzzContext.functions.filter(f => f.startsWith('OH_'));
                if (ndkFunctions.length > 0) {
                    // 标记为NDK Fuzzer（可能没有对应的cpp源文件）
                    this.contextGraph.sourceToFuzzMapping[`NDK:${fuzzBaseName}`] = [fuzzContext.filePath];
                }
            }
        }
        
        // === 策略4: 测试文件 → Mock文件 映射（新增）===
        console.log('   🔍 分析 Test → Mock 映射关系...');
        for (const testContext of this.contextGraph.testContexts) {
            const testDir = path.dirname(testContext.filePath);
            const testContent = testContext.content || '';
            
            // 查找测试文件中包含的 Mock 头文件
            const mockIncludes = [];
            const includeRegex = /#include\s+["<]([^">]*mock[^">]*)["'>]/gi;
            let match;
            
            while ((match = includeRegex.exec(testContent)) !== null) {
                mockIncludes.push(match[1]);
            }
            
            if (mockIncludes.length > 0) {
                // 为每个 Mock 头文件查找对应的 Mock 实现
                const relatedMocks = [];
                
                for (const mockInclude of mockIncludes) {
                    const mockBaseName = path.basename(mockInclude, path.extname(mockInclude));
                    
                    // 在 mockContexts 中查找匹配的 Mock 文件
                    for (const mockContext of this.contextGraph.mockContexts) {
                        const mockFileName = path.basename(mockContext.fileName, path.extname(mockContext.fileName));
                        
                        if (mockFileName === mockBaseName || mockFileName.includes(mockBaseName) || mockBaseName.includes(mockFileName)) {
                            relatedMocks.push({
                                mockFile: mockContext.filePath,
                                mockInclude: mockInclude,
                                mockClasses: mockContext.mockClasses || [],
                                mockMethods: mockContext.mockMethods || []
                            });
                        }
                    }
                }
                
                if (relatedMocks.length > 0) {
                    this.contextGraph.testToMockMapping[testContext.filePath] = relatedMocks;
                }
            }
        }
        
        // === 策略5: 分析 Mock 使用模式 ===
        console.log('   🔍 提取 Mock 使用模式...');
        const mockPatterns = {
            externalServiceMock: [],  // 外部服务 Mock
            systemAbilityMock: [],    // 系统能力 Mock
            ipcMock: [],              // IPC/Binder Mock
            fileIOMock: [],           // 文件 I/O Mock
            databaseMock: []          // 数据库 Mock
        };
        
        for (const [testFile, mocks] of Object.entries(this.contextGraph.testToMockMapping)) {
            for (const mock of mocks) {
                const mockFile = mock.mockFile.toLowerCase();
                const mockClasses = (mock.mockClasses || []).join(' ').toLowerCase();
                
                // 分类 Mock
                if (mockFile.includes('ability') || mockClasses.includes('ability')) {
                    mockPatterns.systemAbilityMock.push({
                        testFile,
                        mockFile: mock.mockFile,
                        mockClasses: mock.mockClasses
                    });
                } else if (mockFile.includes('ipc') || mockFile.includes('binder') || mockClasses.includes('ipc') || mockClasses.includes('binder')) {
                    mockPatterns.ipcMock.push({
                        testFile,
                        mockFile: mock.mockFile,
                        mockClasses: mock.mockClasses
                    });
                } else if (mockFile.includes('file') || mockFile.includes('storage') || mockClasses.includes('file')) {
                    mockPatterns.fileIOMock.push({
                        testFile,
                        mockFile: mock.mockFile,
                        mockClasses: mock.mockClasses
                    });
                } else if (mockFile.includes('database') || mockFile.includes('db') || mockClasses.includes('database')) {
                    mockPatterns.databaseMock.push({
                        testFile,
                        mockFile: mock.mockFile,
                        mockClasses: mock.mockClasses
                    });
                } else {
                    mockPatterns.externalServiceMock.push({
                        testFile,
                        mockFile: mock.mockFile,
                        mockClasses: mock.mockClasses
                    });
                }
            }
        }
        
        this.contextGraph.mockUsagePatterns = mockPatterns;
        
        // 统计
        this.contextGraph.stats.sourceWithTest = Object.keys(this.contextGraph.sourceToTestMapping).length;
        this.contextGraph.stats.sourceWithFuzz = Object.keys(this.contextGraph.sourceToFuzzMapping).length;
        this.contextGraph.stats.testWithMock = Object.keys(this.contextGraph.testToMockMapping).length;
        
        console.log(`   ✅ 映射完成: ${this.contextGraph.stats.sourceWithTest} 个源有测试, ${this.contextGraph.stats.sourceWithFuzz} 个源有Fuzz, ${this.contextGraph.stats.testWithMock} 个测试使用Mock\n`);
    }

    /**
     * 步骤7：分析GN关系图谱
     */
    async analyzeGNRelationships() {
        const gnFiles = new Set();
        
        // 收集所有GN文件
        for (const context of [...this.contextGraph.sourceContexts, 
                                  ...this.contextGraph.testContexts, 
                                  ...this.contextGraph.fuzzContexts]) {
            if (context.sameDirGN) {
                gnFiles.add(JSON.stringify(context.sameDirGN));
            }
            if (context.parentDirGN) {
                gnFiles.add(JSON.stringify(context.parentDirGN));
            }
        }
        
        // 分析GN之间的关系
        for (const gnFileStr of gnFiles) {
            const gnFile = JSON.parse(gnFileStr);
            if (gnFile.content && gnFile.content.deps) {
                this.contextGraph.gnRelationships.push({
                    gnPath: gnFile.path,
                    deps: gnFile.content.deps,
                    external_deps: gnFile.content.external_deps || []
                });
            }
        }
    }

    /**
     * 保存结果
     */
    async saveResults() {
        console.log('\n💾 开始保存结果（分批保存）...\n');
        
        const knowledgeDir = path.join(__dirname, '../core/knowledge');
        
        // 🎯 追加模式：加载现有数据，然后追加 Foundation 数据
        console.log('   📥 加载现有知识库...');
        let existingTests = [];
        let existingFuzz = [];
        let existingMock = [];
        
        // 加载现有的批次文件
        const existingTestFiles = fs.readdirSync(knowledgeDir).filter(f => f.startsWith('ultra-deep-test-'));
        for (const file of existingTestFiles) {
            try {
                const data = JSON.parse(fs.readFileSync(path.join(knowledgeDir, file), 'utf-8'));
                existingTests.push(...data);
            } catch (e) {}
        }
        
        const existingFuzzFiles = fs.readdirSync(knowledgeDir).filter(f => f.startsWith('ultra-deep-fuzz-'));
        for (const file of existingFuzzFiles) {
            try {
                const data = JSON.parse(fs.readFileSync(path.join(knowledgeDir, file), 'utf-8'));
                existingFuzz.push(...data);
            } catch (e) {}
        }
        
        const existingMockFiles = fs.readdirSync(knowledgeDir).filter(f => f.startsWith('ultra-deep-mock-'));
        for (const file of existingMockFiles) {
            try {
                const data = JSON.parse(fs.readFileSync(path.join(knowledgeDir, file), 'utf-8'));
                existingMock.push(...data);
            } catch (e) {}
        }
        
        console.log(`   ✅ 已加载: ${existingTests.length} 个测试, ${existingFuzz.length} 个Fuzz, ${existingMock.length} 个Mock`);
        
        // 合并数据（Foundation追加到已有数据）
        const mergedTests = [...existingTests, ...this.contextGraph.testContexts];
        const mergedFuzz = [...existingFuzz, ...this.contextGraph.fuzzContexts];
        const mergedMock = [...existingMock, ...this.contextGraph.mockContexts];
        
        console.log(`   ➕ 追加后: ${mergedTests.length} 个测试, ${mergedFuzz.length} 个Fuzz, ${mergedMock.length} 个Mock\n`);
        
        // 删除旧的批次文件
        [...existingTestFiles, ...existingFuzzFiles, ...existingMockFiles].forEach(file => {
            fs.unlinkSync(path.join(knowledgeDir, file));
        });
        
        // 保存合并后的测试上下文（分批）
        const testBatchSize = 1000;
        for (let i = 0; i < mergedTests.length; i += testBatchSize) {
            const batch = mergedTests.slice(i, i + testBatchSize);
            const batchPath = path.join(knowledgeDir, `ultra-deep-test-${Math.floor(i / testBatchSize)}.json`);
            fs.writeFileSync(batchPath, JSON.stringify(batch, null, 2), 'utf-8');
            console.log(`   已保存测试批次 ${Math.floor(i / testBatchSize) + 1}: ${batch.length} 个文件`);
        }
        
        // 保存合并后的Fuzz上下文（分批）
        const fuzzBatchSize = 500;
        for (let i = 0; i < mergedFuzz.length; i += fuzzBatchSize) {
            const batch = mergedFuzz.slice(i, i + fuzzBatchSize);
            const batchPath = path.join(knowledgeDir, `ultra-deep-fuzz-${Math.floor(i / fuzzBatchSize)}.json`);
            fs.writeFileSync(batchPath, JSON.stringify(batch, null, 2), 'utf-8');
            console.log(`   已保存Fuzz批次 ${Math.floor(i / fuzzBatchSize) + 1}: ${batch.length} 个文件`);
        }
        
        // 保存合并后的Mock上下文（分批）
        const mockBatchSize = 500;
        for (let i = 0; i < mergedMock.length; i += mockBatchSize) {
            const batch = mergedMock.slice(i, i + mockBatchSize);
            const batchPath = path.join(knowledgeDir, `ultra-deep-mock-${Math.floor(i / mockBatchSize)}.json`);
            fs.writeFileSync(batchPath, JSON.stringify(batch, null, 2), 'utf-8');
            console.log(`   已保存Mock批次 ${Math.floor(i / mockBatchSize) + 1}: ${batch.length} 个文件`);
        }
        
        // 保存索引和映射关系（较小）
        const indexData = {
            stats: this.contextGraph.stats,
            sourceToTestMapping: this.contextGraph.sourceToTestMapping,
            sourceToFuzzMapping: this.contextGraph.sourceToFuzzMapping,
            gnRelationships: this.contextGraph.gnRelationships,
            testBatches: Math.ceil(this.contextGraph.testContexts.length / testBatchSize),
            fuzzBatches: Math.ceil(this.contextGraph.fuzzContexts.length / fuzzBatchSize),
            mockBatches: Math.ceil(this.contextGraph.mockContexts.length / mockBatchSize)
        };
        
        // 更新索引文件的统计信息
        indexData.stats.totalTests = mergedTests.length;
        indexData.stats.totalFuzz = mergedFuzz.length;
        indexData.stats.totalMock = mergedMock.length;
        indexData.testBatches = Math.ceil(mergedTests.length / testBatchSize);
        indexData.fuzzBatches = Math.ceil(mergedFuzz.length / fuzzBatchSize);
        indexData.mockBatches = Math.ceil(mergedMock.length / mockBatchSize);
        
        const indexPath = path.join(knowledgeDir, 'ultra-deep-index.json');
        fs.writeFileSync(indexPath, JSON.stringify(indexData, null, 2), 'utf-8');
        console.log(`\n   ✅ 已更新索引文件: ultra-deep-index.json`);
        
        // 计算总大小
        let totalSize = 0;
        const files = fs.readdirSync(knowledgeDir).filter(f => f.startsWith('ultra-deep-'));
        for (const file of files) {
            totalSize += fs.statSync(path.join(knowledgeDir, file)).size;
        }
        
        console.log(`\n💾 保存完成！`);
        console.log(`   总文件数: ${files.length}`);
        console.log(`   总大小: ${(totalSize / 1024 / 1024).toFixed(2)} MB\n`);
    }

    /**
     * 打印摘要
     */
    printSummary() {
        console.log('\n📊 ═══════════════════════════════════════════════════════');
        console.log('                超深度上下文学习摘要');
        console.log('═══════════════════════════════════════════════════════\n');
        
        console.log('【文件统计】');
        console.log(`  • 源文件上下文:         ${this.contextGraph.sourceContexts.length} 个`);
        console.log(`  • 测试文件上下文:       ${this.contextGraph.testContexts.length} 个`);
        console.log(`  • Fuzz文件上下文:       ${this.contextGraph.fuzzContexts.length} 个`);
        console.log(`  • Mock文件上下文:       ${this.contextGraph.mockContexts.length} 个\n`);
        
        console.log('【映射关系】');
        console.log(`  • 源→测试映射:          ${Object.keys(this.contextGraph.sourceToTestMapping).length} 对`);
        console.log(`  • 源→Fuzz映射:          ${Object.keys(this.contextGraph.sourceToFuzzMapping).length} 对`);
        console.log(`  • GN关系:               ${this.contextGraph.gnRelationships.length} 个\n`);
        
        console.log('【覆盖率】');
        const testCoverage = this.contextGraph.sourceContexts.length > 0 ?
            (this.contextGraph.stats.sourceWithTest / this.contextGraph.sourceContexts.length * 100).toFixed(2) : 0;
        const fuzzCoverage = this.contextGraph.sourceContexts.length > 0 ?
            (this.contextGraph.stats.sourceWithFuzz / this.contextGraph.sourceContexts.length * 100).toFixed(2) : 0;
        
        console.log(`  • 有测试的源文件:       ${this.contextGraph.stats.sourceWithTest} (${testCoverage}%)`);
        console.log(`  • 有Fuzz的源文件:       ${this.contextGraph.stats.sourceWithFuzz} (${fuzzCoverage}%)`);
        
        console.log('\n═══════════════════════════════════════════════════════\n');
    }

    // ============ 辅助方法 ============

    findSourceFiles(projectRoot, excludeDirs) {
        const files = [];
        const scanDir = (dir, depth = 0) => {
            if (depth > 10 || files.length >= 5000) return; // 每个项目最多5000个源文件（Foundation项目通常很大）
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    const fullPath = path.join(dir, entry.name);
                    
                    if (entry.isDirectory()) {
                        if (!excludeDirs.includes(entry.name) && !entry.name.startsWith('.')) {
                            scanDir(fullPath, depth + 1);
                        }
                    } else if (entry.isFile()) {
                        if ((entry.name.endsWith('.cpp') || entry.name.endsWith('.cc')) &&
                            !entry.name.includes('_test') && !entry.name.includes('_fuzzer')) {
                            files.push(fullPath);
                        }
                    }
                }
            } catch (e) {}
        };
        
        scanDir(projectRoot);
        return files;
    }

    findTestFiles(testDir) {
        const files = [];
        const scanDir = (dir) => {
            if (files.length >= 500) return; // 提高限制
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    const fullPath = path.join(dir, entry.name);
                    
                    if (entry.isDirectory()) {
                        scanDir(fullPath);
                    } else if (entry.isFile()) {
                        if ((entry.name.endsWith('_test.cpp') || entry.name.endsWith('_unittest.cpp'))) {
                            files.push(fullPath);
                        }
                    }
                }
            } catch (e) {}
        };
        
        scanDir(testDir);
        return files;
    }

    findFuzzFiles(fuzzDir) {
        const files = [];
        const scanDir = (dir) => {
            if (files.length >= 200) return; // 提高限制
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    const fullPath = path.join(dir, entry.name);
                    
                    if (entry.isDirectory()) {
                        scanDir(fullPath);
                    } else if (entry.isFile()) {
                        if (entry.name.endsWith('_fuzzer.cpp')) {
                            files.push(fullPath);
                        }
                    }
                }
            } catch (e) {}
        };
        
        scanDir(fuzzDir);
        return files;
    }

    findMockFiles(projectRoot) {
        const files = [];
        
        // 查找多个可能的mock目录
        const mockDirs = [
            path.join(projectRoot, 'mock'),
            path.join(projectRoot, 'mocks'),
            path.join(projectRoot, 'test', 'mock'),
            path.join(projectRoot, 'test', 'mocks'),
            path.join(projectRoot, 'test', 'unittest', 'mock')
        ];
        
        const scanDir = (dir) => {
            if (files.length >= 500) return; // 提高限制
            
            try {
                const entries = fs.readdirSync(dir, { withFileTypes: true });
                
                for (const entry of entries) {
                    const fullPath = path.join(dir, entry.name);
                    
                    if (entry.isDirectory()) {
                        scanDir(fullPath);
                    } else if (entry.isFile()) {
                        // 查找Mock文件（文件名包含mock的.h或.cpp）
                        if ((entry.name.includes('mock') || entry.name.includes('Mock')) &&
                            (entry.name.endsWith('.cpp') || entry.name.endsWith('.h'))) {
                            files.push(fullPath);
                        }
                    }
                }
            } catch (e) {}
        };
        
        for (const mockDir of mockDirs) {
            if (fs.existsSync(mockDir)) {
                scanDir(mockDir);
            }
        }
        
        return files;
    }

    parseGNFile(gnPath) {
        const content = this.safeReadFile(gnPath);
        if (!content) return null;
        
        return {
            sources: this.extractGNArray(content, 'sources'),
            deps: this.extractGNArray(content, 'deps'),
            external_deps: this.extractGNArray(content, 'external_deps'),
            include_dirs: this.extractGNArray(content, 'include_dirs'),
            module_out_path: this.extractGNField(content, 'module_out_path'),
            fuzz_config_file: this.extractGNField(content, 'fuzz_config_file')
        };
    }

    extractIncludes(code) {
        const includes = [];
        const regex = /#include\s+["<]([^">]+)[">]/g;
        let match;
        while ((match = regex.exec(code)) !== null) {
            includes.push(match[1]);
        }
        return includes.slice(0, 20); // 最多20个
    }

    extractFunctionSignatures(code) {
        const functions = [];
        // 简化的函数签名提取
        const regex = /(?:^|\n)\s*(?:static\s+)?(?:virtual\s+)?(?:\w+(?:\s*\*|\s*&)?)\s+(\w+)\s*\(/gm;
        let match;
        while ((match = regex.exec(code)) !== null) {
            if (!['if', 'while', 'for', 'switch', 'return'].includes(match[1])) {
                functions.push(match[1]);
            }
        }
        return functions.slice(0, 30); // 最多30个
    }

    extractClasses(code) {
        const classes = [];
        const regex = /class\s+(\w+)/g;
        let match;
        while ((match = regex.exec(code)) !== null) {
            classes.push(match[1]);
        }
        return classes;
    }

    extractNamespaces(code) {
        const namespaces = [];
        const regex = /namespace\s+(\w+)/g;
        let match;
        while ((match = regex.exec(code)) !== null) {
            namespaces.push(match[1]);
        }
        return namespaces;
    }

    extractHWTestCases(code) {
        const cases = [];
        const regex = /HWTEST_F\s*\(\s*(\w+)\s*,\s*(\w+)\s*,/g;
        let match;
        while ((match = regex.exec(code)) !== null) {
            cases.push({ suite: match[1], case: match[2] });
        }
        return cases;
    }

    extractGNArray(content, fieldName) {
        const items = [];
        const regex = new RegExp(`${fieldName}\\s*(?:=|\\+=)\\s*\\[([^\\]]*(?:\\[[^\\]]*\\][^\\]]*)*)\\]`, 'gs');
        let match;
        
        while ((match = regex.exec(content)) !== null) {
            const itemsStr = match[1];
            const itemMatches = itemsStr.match(/"([^"]+)"/g);
            if (itemMatches) {
                items.push(...itemMatches.map(m => m.replace(/"/g, '')));
            }
        }
        
        return items.slice(0, 50); // 最多50个
    }

    extractGNField(content, fieldName) {
        const regex = new RegExp(`${fieldName}\\s*=\\s*"([^"]+)"`, 'i');
        const match = content.match(regex);
        return match ? match[1] : '';
    }

    safeReadFile(filePath) {
        try {
            return fs.readFileSync(filePath, 'utf-8');
        } catch (e) {
            return null;
        }
    }

    /**
     * 🔥 深入分析测试函数内容
     */
    async deepAnalyzeTestFunctions(testFile, context) {
        const content = this.safeReadFile(testFile);
        if (!content) return;
        
        context.testFunctionDetails = {
            hwtestCases: [],           // HWTEST_F 完整内容
            mockUsage: [],             // Mock使用模式
            expectCalls: [],           // EXPECT_CALL 模式
            assertions: [],            // 断言模式
            setupTeardown: null,       // SetUp/TearDown
            includedHeaders: [],       // 引用的头文件（详细分析）
            calledFunctions: [],       // 调用的被测函数
            testDataPatterns: []       // 测试数据构造模式
        };
        
        // 1. 提取完整的 HWTEST_F 函数体
        const hwtestRegex = /HWTEST_F\s*\(([^,]+),\s*([^,]+),\s*([^)]+)\)\s*\{([\s\S]*?)(?=\nHWTEST_F|\nTEST_F|\n}\n|\Z)/g;
        let match;
        while ((match = hwtestRegex.exec(content)) !== null) {
            const functionBody = match[4];
            context.testFunctionDetails.hwtestCases.push({
                suite: match[1].trim(),
                testName: match[2].trim(),
                level: match[3].trim(),
                bodyPreview: functionBody.substring(0, 500), // 前500字符
                fullBody: functionBody.length > 2000 ? functionBody.substring(0, 2000) : functionBody,
                // 分析函数体内容
                hasExpectCall: /EXPECT_CALL/.test(functionBody),
                hasExpectEq: /EXPECT_EQ/.test(functionBody),
                hasExpectNe: /EXPECT_NE/.test(functionBody),
                hasExpectTrue: /EXPECT_TRUE/.test(functionBody),
                hasExpectFalse: /EXPECT_FALSE/.test(functionBody),
                hasAssertEq: /ASSERT_EQ/.test(functionBody),
                hasMockObject: /Mock|mock/.test(functionBody),
                calledFunctions: this.extractCalledFunctions(functionBody)
            });
        }
        
        // 2. 提取 Mock 使用模式
        const mockCallRegex = /EXPECT_CALL\s*\(\s*([^,]+),\s*([^)]+)\)/g;
        while ((match = mockCallRegex.exec(content)) !== null) {
            context.testFunctionDetails.mockUsage.push({
                mockObject: match[1].trim(),
                mockMethod: match[2].trim()
            });
        }
        
        // 3. 提取断言模式
        const assertionRegex = /(EXPECT_\w+|ASSERT_\w+)\s*\(([^;]+)\);/g;
        while ((match = assertionRegex.exec(content)) !== null) {
            context.testFunctionDetails.assertions.push({
                type: match[1],
                expression: match[2].trim().substring(0, 100)
            });
        }
        
        // 4. 提取 SetUp 和 TearDown
        const setupRegex = /void\s+SetUp\s*\(\s*\)\s*override\s*\{([\s\S]*?)(?=\n\s*void\s+|\n\s*\})/;
        const teardownRegex = /void\s+TearDown\s*\(\s*\)\s*override\s*\{([\s\S]*?)(?=\n\s*void\s+|\n\s*\})/;
        const setupMatch = content.match(setupRegex);
        const teardownMatch = content.match(teardownRegex);
        
        if (setupMatch || teardownMatch) {
            context.testFunctionDetails.setupTeardown = {
                hasSetUp: !!setupMatch,
                hasTearDown: !!teardownMatch,
                setUpContent: setupMatch ? setupMatch[1].substring(0, 500) : '',
                tearDownContent: teardownMatch ? teardownMatch[1].substring(0, 500) : ''
            };
        }
        
        // 5. 详细分析引用的头文件
        const includeRegex = /#include\s+["<]([^">]+)[">]/g;
        while ((match = includeRegex.exec(content)) !== null) {
            const header = match[1];
            context.testFunctionDetails.includedHeaders.push({
                header: header,
                isSystemHeader: match[0].includes('<'),
                isTestHeader: header.includes('gtest') || header.includes('gmock'),
                isMockHeader: header.includes('mock')
            });
        }
        
        // 6. 分析测试数据构造模式
        const testDataPatterns = [
            { pattern: /std::vector<.*?>\s+\w+\s*=\s*\{/, name: 'vector_initialization' },
            { pattern: /std::string\s+\w+\s*=\s*"/, name: 'string_initialization' },
            { pattern: /int\s+\w+\s*=\s*\d+/, name: 'int_initialization' },
            { pattern: /auto\s+\w+\s*=\s*std::make_shared/, name: 'shared_ptr_creation' },
            { pattern: /new\s+\w+\(/, name: 'heap_allocation' }
        ];
        
        for (const { pattern, name } of testDataPatterns) {
            if (pattern.test(content)) {
                context.testFunctionDetails.testDataPatterns.push(name);
            }
        }
    }

    /**
     * 🔥 深入分析Fuzzer函数内容
     */
    async deepAnalyzeFuzzerFunctions(fuzzFile, context) {
        const content = this.safeReadFile(fuzzFile);
        if (!content) return;
        
        context.fuzzerFunctionDetails = {
            fuzzerFunctions: [],       // Fuzzer函数完整内容
            includedHeaders: [],       // 引用的头文件（详细分析）
            calledNDKInterfaces: [],   // 调用的NDK接口
            calledFunctions: [],       // 调用的被测函数
            dataConstructionPatterns: [], // 数据构造模式
            fuzzerFrameworkUsage: {}   // Fuzzer框架使用情况
        };
        
        // 1. 提取 LLVMFuzzerTestOneInput 函数
        const fuzzerFuncRegex = /bool\s+(\w*Fuzz\w*TestOneInput)\s*\(const uint8_t\s*\*\s*data,\s*size_t\s+size\)\s*\{([\s\S]*?)(?=\n}\n|\Z)/g;
        let match;
        while ((match = fuzzerFuncRegex.exec(content)) !== null) {
            const functionBody = match[2];
            context.fuzzerFunctionDetails.fuzzerFunctions.push({
                funcName: match[1],
                bodyPreview: functionBody.substring(0, 500),
                fullBody: functionBody.length > 2000 ? functionBody.substring(0, 2000) : functionBody,
                // 分析函数体内容
                hasSizeCheck: /if\s*\(.*?size/.test(functionBody),
                hasDataParsing: /GetData<|GetObject<|ConsumeBytes/.test(functionBody),
                hasNDKCall: /\bOH_\w+/.test(functionBody),
                calledFunctions: this.extractCalledFunctions(functionBody),
                calledNDKInterfaces: this.extractNDKInterfaces(functionBody)
            });
        }
        
        // 2. 详细分析引用的头文件
        const includeRegex = /#include\s+["<]([^">]+)[">]/g;
        while ((match = includeRegex.exec(content)) !== null) {
            const header = match[1];
            context.fuzzerFunctionDetails.includedHeaders.push({
                header: header,
                isSystemHeader: match[0].includes('<'),
                isNDKHeader: header.startsWith('OH_') || header.includes('ndk'),
                isFuzzerHeader: header.includes('fuzzer') || header.includes('FuzzedDataProvider')
            });
        }
        
        // 3. 提取调用的NDK接口
        const ndkRegex = /\b(OH_\w+)\s*\(/g;
        while ((match = ndkRegex.exec(content)) !== null) {
            context.fuzzerFunctionDetails.calledNDKInterfaces.push(match[1]);
        }
        
        // 4. 分析数据构造模式
        const dataPatterns = [
            { pattern: /FuzzedDataProvider/, name: 'FuzzedDataProvider' },
            { pattern: /GetData<\w+>/, name: 'GetData_template' },
            { pattern: /GetObject<\w+>/, name: 'GetObject_template' },
            { pattern: /ConsumeBytes/, name: 'ConsumeBytes' },
            { pattern: /ConsumeIntegral/, name: 'ConsumeIntegral' },
            { pattern: /ConsumeString/, name: 'ConsumeString' },
            { pattern: /ConsumeBool/, name: 'ConsumeBool' }
        ];
        
        for (const { pattern, name } of dataPatterns) {
            if (pattern.test(content)) {
                context.fuzzerFunctionDetails.dataConstructionPatterns.push(name);
            }
        }
        
        // 5. 分析Fuzzer框架使用
        context.fuzzerFunctionDetails.fuzzerFrameworkUsage = {
            usesFuzzedDataProvider: /FuzzedDataProvider/.test(content),
            usesGetData: /GetData</.test(content),
            usesGetObject: /GetObject</.test(content),
            hasSizeValidation: /size\s*<|size\s*>|size\s*==/.test(content),
            hasNullCheck: /nullptr|NULL/.test(content)
        };
    }

    /**
     * 从函数体中提取被调用的函数
     */
    extractCalledFunctions(functionBody) {
        const functions = [];
        // 匹配函数调用模式：functionName(
        const regex = /\b([a-zA-Z_]\w*)\s*\(/g;
        let match;
        const excludedKeywords = ['if', 'while', 'for', 'switch', 'return', 'sizeof', 'EXPECT_', 'ASSERT_', 'HWTEST_F'];
        
        while ((match = regex.exec(functionBody)) !== null) {
            const funcName = match[1];
            if (!excludedKeywords.some(kw => funcName.startsWith(kw))) {
                functions.push(funcName);
            }
        }
        
        // 去重并限制数量
        return [...new Set(functions)].slice(0, 30);
    }

    /**
     * 提取NDK接口调用
     */
    extractNDKInterfaces(functionBody) {
        const ndkInterfaces = [];
        const regex = /\b(OH_\w+)\s*\(/g;
        let match;
        
        while ((match = regex.exec(functionBody)) !== null) {
            ndkInterfaces.push(match[1]);
        }
        
        return [...new Set(ndkInterfaces)];
    }

    /**
     * 🔥 深入分析Mock类实现
     */
    async deepAnalyzeMockImplementation(mockFile, context) {
        const content = this.safeReadFile(mockFile);
        if (!content) return;
        
        context.mockImplementationDetails = {
            mockClasses: [],           // Mock类定义
            mockMethods: [],           // MOCK_METHOD定义
            includedHeaders: [],       // 引用的头文件
            inheritedClasses: [],      // 继承的类
            mockPatterns: []           // Mock模式
        };
        
        // 1. 提取Mock类定义
        const mockClassRegex = /class\s+(\w*Mock\w*)\s*:\s*public\s+([^{]+)\s*\{([\s\S]*?)(?=\nclass|\n\};\n|\Z)/g;
        let match;
        while ((match = mockClassRegex.exec(content)) !== null) {
            const className = match[1];
            const baseClass = match[2].trim();
            const classBody = match[3];
            
            context.mockImplementationDetails.mockClasses.push({
                className: className,
                baseClass: baseClass,
                bodyPreview: classBody.substring(0, 1000)
            });
            
            // 提取Mock方法
            const mockMethodRegex = /MOCK_METHOD\d*\s*\(([^;]+)\);/g;
            let methodMatch;
            while ((methodMatch = mockMethodRegex.exec(classBody)) !== null) {
                context.mockImplementationDetails.mockMethods.push({
                    className: className,
                    methodSignature: methodMatch[1].trim()
                });
            }
        }
        
        // 2. 提取继承的类
        const inheritRegex = /class\s+\w+\s*:\s*public\s+([^{]+)/g;
        while ((match = inheritRegex.exec(content)) !== null) {
            const baseClasses = match[1].split(',').map(c => c.trim());
            context.mockImplementationDetails.inheritedClasses.push(...baseClasses);
        }
        
        // 3. 提取引用的头文件
        const includeRegex = /#include\s+["<]([^">]+)[">]/g;
        while ((match = includeRegex.exec(content)) !== null) {
            const header = match[1];
            context.mockImplementationDetails.includedHeaders.push({
                header: header,
                isSystemHeader: match[0].includes('<'),
                isGMockHeader: header.includes('gmock')
            });
        }
        
        // 4. 分析Mock模式
        const mockPatterns = [
            { pattern: /MOCK_METHOD0/, name: 'MOCK_METHOD0' },
            { pattern: /MOCK_METHOD1/, name: 'MOCK_METHOD1' },
            { pattern: /MOCK_METHOD2/, name: 'MOCK_METHOD2' },
            { pattern: /MOCK_METHOD3/, name: 'MOCK_METHOD3' },
            { pattern: /MOCK_METHOD/, name: 'MOCK_METHOD_general' },
            { pattern: /MOCK_CONST_METHOD/, name: 'MOCK_CONST_METHOD' },
            { pattern: /ON_CALL/, name: 'ON_CALL' },
            { pattern: /EXPECT_CALL/, name: 'EXPECT_CALL' }
        ];
        
        for (const { pattern, name } of mockPatterns) {
            if (pattern.test(content)) {
                context.mockImplementationDetails.mockPatterns.push(name);
            }
        }
    }
}

// 运行
const learner = new UltraDeepContextLearner('./OHCode');
learner.run().then(() => {
    console.log('🎉 超深度上下文学习完成！\n');
    process.exit(0);
}).catch(err => {
    console.error('❌ 错误:', err);
    process.exit(1);
});

